#include "simulator.h"
#include <sys/ipc.h>
#include <stdio.h>

int receive_message(int s, Message *msg){
  void *buffer = (void*)msg;
  int rBytes, rv;
  for(rBytes = 0; rBytes < sizeof(*msg);rBytes+=rv){
    if((rv = recv(s, buffer+rBytes, sizeof(*msg)-rBytes, 0)) <= 0){
      perror("Cannot receive");
      return -1;
    }
  }
  return 1;
}

int dequeue_message(int qid, long type, Message * qbuf) {
  int result, length;

  /* The length is essentially the size of the structure minus sizeof(mtype) */
  length = sizeof (message_buf) - sizeof (long);

  if ((result = msgrcv(qid, qbuf, length, type, 0)) == -1) {
    return (-1);
  }

  return (result);
}

int enqueue_message(int qid, Message * qbuf) {
  int result, length;

  /* The length is essentially the size of the structure minus sizeof(mtype) */
  length = sizeof (message_buf) - sizeof (long);

  if ((result = msgsnd(qid, qbuf, length, 0)) == -1) {
    return (-1);
  }

  return (result);
}

int dequeue_message_nowait(int qid, long type, Message * qbuf) {
  int result, length;

  /* The length is essentially the size of the structure minus sizeof(mtype) */
  length = sizeof (message_buf) - sizeof (long);

  if ((result = msgrcv(qid, qbuf, length, type, IPC_NOWAIT)) == -1) {
    return (-1);
  }

  return (result);
}
void textcolor(int attr, int fg, int bg) {
  char command[13];

  /* Command is the control command to the terminal */
  sprintf(command, "%c[%d;%dm", 0x1B, attr, fg + 30);
  printf("%s", command);
}

void output(char *msg, int type) {
  switch(type){
    case ERROR:textcolor(BRIGHT, RED, WHITE);break;
    case INFO:textcolor(RESET, CYAN, WHITE);break;
    case MSG_SENT: textcolor(RESET, YELLOW,WHITE);break;
    case MSG_RCVD:textcolor(RESET, GREEN,WHITE);break;
    case COMPUTING:textcolor(RESET, MAGENTA, WHITE);break;
    case IMP_INFO:textcolor(BRIGHT, CYAN, WHITE);break;
    case NIMP:textcolor(BRIGHT, BLACK , WHITE);break;
  }
  puts(msg);
  textcolor(RESET,WHITE,WHITE);
}
